package edu.cmu.cs.cs214.hw9.client.controllers.eventhandlers;

import java.util.Date;

import javax.swing.SwingWorker;

import edu.cmu.cs.cs214.hw9.client.controllers.BackendCacheAdapter;
import edu.cmu.cs.cs214.hw9.client.controllers.SessionController;
import edu.cmu.cs.cs214.hw9.datatypes.Status;
import edu.cmu.cs.cs214.hw9.datatypes.User;

/**
 * Post a status to the currently logged in user's wall.
 */
public class PostStatusHandler extends SessionEventHandler {
	/**
	 * Post the status in a separate thread to prevent swing from freezing.
	 */
	private class PostStatusWorker extends SwingWorker<Boolean, Void> {
		private BackendCacheAdapter model;
		private User currentUser;
		private String status;
		
		/**
		 * Constructs a new request to insert the provided status into the database.
		 * 
		 * @param status Status to post/insert into the database.
		 */
		public PostStatusWorker(String status) {
			this.status = status;
			currentUser = controller.getCurrentUser();
			model = controller.getModel();
		}
		
		/**
		 * Insert the status into the database.
		 * 
		 * @return true if successful; false otherwise.
		 */
		public Boolean doInBackground() {
			Status newStatus = new Status(status, currentUser, new Date());
			return model.storeStatus(newStatus);
		}
	};
	
	/**
	 * Set the current session controller to the provided controller.
	 * 
	 * @param controller Controller to associate with this event handler.
	 */
	public PostStatusHandler(SessionController controller) { super(controller); }
	
	/**
	 * Create the post status request and run it in an outside thread.
	 * 
	 * @param param Status to post, as a string.
	 */
	public void handleEvent(Object param) {
		PostStatusWorker postStatusWorker = new PostStatusWorker((String) param);
		postStatusWorker.execute();
	}
}
